package com.shengwei.truck.driver.view.ui;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;
import com.google.gson.JsonSyntaxException;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.model.DataSource;
import com.shengwei.truck.driver.net.NetWorkUtils;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.selfview.CustomProgress;
import com.shengwei.truck.driver.view.ui.mine.userinfo.LoginActivity;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

/**
 * Fragment碎片UI的基类，在各子类Fragment里需要重复写的代码，统一都放在这里，通过继承此基类重用这些代码
 */
public abstract class BaseFragment <VM extends ViewModel,VDB extends ViewDataBinding> extends  Fragment {
    protected VM mViewModel;
    protected VDB mDataBinding;
    protected CustomProgress dialog;
    protected Toolbar mToolbar;
    protected Context mContext;
    protected static String TAG = "BaseFragment";


    @Override
    public void onAttach(Context context) {
        Log.i(TAG,"onAttach");
        mContext = context;
        super.onAttach(context);
    }
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = DataBindingUtil.inflate(inflater,getContentViewId(),container,false);
        //创建每一个Activity对应的ViewModel
        createViewModel();
        addLifeCycleObserver();
        View rootView = mDataBinding.getRoot();
        mToolbar = rootView.findViewById(R.id.toolbar);
        String title = this.getResources().getString(R.string.bottom_tab_mine);
        setToolBar(false,true,title);
        return rootView;
    }


    /**
     * 配置页面标题栏目
     * @param isSHowBack:是否显示返回箭头
     * @param isDisplayTitle:是否显示标题
     */
    public void setToolBar(boolean isSHowBack,boolean isDisplayTitle,String title)
    {
        if(mToolbar != null) {
            ((AppCompatActivity) mContext).setSupportActionBar(mToolbar);
            ActionBar actionBar =  ((AppCompatActivity) mContext).getSupportActionBar();
            setToolbarBack(actionBar,isSHowBack);

            //自定义标题显示
            if(isDisplayTitle) {
                actionBar.setDisplayShowTitleEnabled(true);
                actionBar.setTitle(title);
           /*     TextView tvTtile =  mToolbar.findViewById(R.id.tvTitle);
                if(tvTtile != null)
                    tvTtile.setText(title);*/
            }
            else{
                actionBar.setDisplayShowTitleEnabled(false);//屏蔽掉系统的标题
            }
        }
    }

    public void setBackClick() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }
    /**
     * 设置Toolbar是否显示返回键
     * @param actionBar
     * @param isShowBack
     */
    public void setToolbarBack(ActionBar actionBar,boolean isShowBack)
    {
        actionBar.setDisplayHomeAsUpEnabled(isShowBack);
        if(isShowBack) {
            setBackClick();
        }
    }
    /**
     * 根据泛型类的第一个参数VM传递过来的具体类型，new出这个具体类型的viewModel
     * 如new出 loginViewModel 与 HomeViewModel
     */
    public void createViewModel()
    {
        if(mViewModel == null) {
            Class myViewModelClass;
            Type type = getClass().getGenericSuperclass();
            if(type instanceof ParameterizedType) {
                myViewModelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
            }
            else {
                myViewModelClass = AndroidViewModel.class;
            }
            mViewModel = (VM)ViewModelProviders.of(this).get(myViewModelClass);
        }
        return;
    }


    public void showLoading(String msg){
        if (dialog == null) {
            dialog = CustomProgress.show(getActivity(), "", true, null);
        }
        if (!TextUtils.isEmpty(msg)) {
            dialog.setMessage(msg);
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }
    /*
     * 封装了请求接口过程中，当处于各种状态时，做出的处理，如显示与隐藏加载框的时机等。
     * 其中 “成功状态” 时的回调处理函数 单独实现在Activity页面里，因为要使用成功时返回的数据。
     * @param <T>
     */
    /**
     * 封装了请求接口过程中，当处于各种状态时，做出的处理，如显示与隐藏加载框的时机等。
     * 其中 “成功状态” 时的回调处理函数 单独实现在Activity页面里，因为要使用成功时返回的数据。
     * @param <T>
     */
    public abstract class OnCallback<T> implements Result.OnHandleCallback<T> {
        @Override
        public void onLoading(String msg) {
            showLoading(msg);
        }

        @Override
        public void onError(Throwable throwable) {
            WeakReference<Context> contextWeakReference =  new WeakReference<>(getActivity());
            if (!NetWorkUtils.isNetworkConnected(getActivity())) {
                MyToast.showToastCenter(contextWeakReference,getResources().getString(R.string.result_network_error),Toast.LENGTH_SHORT,true);
                return;
            }
            if (throwable instanceof ConnectException) {
                MyToast.showToastCenter(contextWeakReference,getResources().getString(R.string.result_server_error),Toast.LENGTH_SHORT,true);
            } else if (throwable instanceof SocketTimeoutException) {
                MyToast.showToastCenter(contextWeakReference,getResources().getString(R.string.result_server_timeout),Toast.LENGTH_SHORT,true);
            } else if (throwable instanceof JsonSyntaxException) {
                MyToast.showToastCenter(contextWeakReference,getResources().getString(R.string.parse_error),Toast.LENGTH_SHORT,true);
            } else {
                MyToast.showToastCenter(contextWeakReference,getResources().getString(R.string.result_empty_error),Toast.LENGTH_SHORT,true);
            }
            dismissDlg();
        }

        @Override
        public void onFailure(String msg) {
            MyLogCat.i(TAG,msg);
            String[] errMsg = msg.split(";");
            int code = Integer.parseInt(errMsg[0]);
            String tip = errMsg[1];
            WeakReference<Context> contextWeakReference = new WeakReference<>(getActivity().getApplicationContext());
            MyToast.showToastCenter(contextWeakReference,tip,Toast.LENGTH_LONG,true);
            //401token过时,403没有权限
             if(code == 401 || code == 403){
                User user = User.getInstance(getActivity().getApplicationContext());
                user.setToken("");
                Intent i = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
                startActivity(i);
            }
            dismissDlg();
        }
        @Override
        public void onCompleted() {
            dismissDlg();
        }
        @Override
        public void onProgress(int precent, long total) {
        }
        /**
         * 请求网络取消了
         */
        @Override
        public void onCancel() {
            dismissDlg();
        }
    }

    public void dismissDlg() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public abstract int getContentViewId();

    /**
     * 让DataSource能感知Fragment的生命周期，在Fragment.onstop的时候，DataSource中的某些函数会自动执行,
     *  这里用到的正是Android JetPack架构组件中的 “LifeCycle”.
     */
    protected void addLifeCycleObserver()
    {
        getLifecycle().addObserver(DataSource.getSingleInstance());
    }
}